#include "qbinaryrpc_request.h"
#include "qbinaryrpc_statics.h"

using namespace qbinaryrpc;

Request::Request() : is_null(true), id(-1) {}

Request::Request(int id, 
                 const QString &method_name, 
                 const QVariantList &parameters)
    : id(id),
      is_null(false),
      method_name(method_name),
      parameters(parameters) {}

int Request::getId() const {
  return id;
}

bool Request::isNull() const {
  return is_null;
}

QString Request::getMethodName() const {
  return method_name;
}

QList<QVariant> Request::getParameters() const {
  return parameters;
}

bool Request::setContent(const QByteArray &massive, int &now_position) {
  int massive_size(massive.size()), id_temp;
  if(Statics::decodeInt32(massive,
                          massive_size - 1,
                          now_position,
                          id_temp) == false) return false;
  int length_packet;
  if(Statics::decodeInt32(massive,
                          massive_size - 1,
                          now_position,
                          length_packet) == false) return false;
  int max_position(now_position + length_packet - 9);
  QString method_name_temp;
  if(Statics::decodeString(massive,
                           max_position,
                           now_position,
                           method_name_temp) == false) return false;
  if(method_name_temp.isEmpty()) return false;
  QVariantList parameters_temp;
  while(now_position < max_position) {
    QVariant parameter;
    if(Statics::decodeValue(massive,
                            max_position,
                            now_position,
                            &parameter)) {
      parameters_temp.push_back(parameter);
    } else {
      return false;
    }
  }
  id = id_temp;
  is_null = false;
  method_name = method_name_temp;
  parameters = parameters_temp;
  return true;
}

QByteArray Request::composeRequest() const {
  QByteArray body;
  Statics::encodeString(method_name, body);
  foreach (QVariant parameter, parameters)
    if(Statics::encodeValue(parameter, body) == false)
      return QByteArray();
  QByteArray header;
  Statics::encodeInt32(id, header);
  Statics::encodeInt32(body.size() + 8, header);
  return header + body;
}
